import store from '../store/index';
import {
    setupMarker
} from "../api/common.js";
import {
    showLoading,
    hideLoading
} from './loading';


const formatTime = date => {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()

    const time = [
        [year, month, day].map(formatNumber).join('-'), [hour, minute, second].map(formatNumber).join(':')
    ]
    return time
}

const formatNumber = n => {
    n = n.toString()
    return n[1] ? n : '0' + n
}

/*函数节流*/
function throttleFunc(func, marginTime) {
    if (marginTime == undefined || marginTime == null) {
        marginTime = 1700
    }
    let lastTime = null
    return function() {
        let currentTime = +new Date()
        if (currentTime - lastTime > marginTime || !lastTime) {
            func.apply(this, arguments)
            lastTime = currentTime
        }
    }
}

/*函数防抖*/
function debounce(fn, interval) {
    let that = this;

    if (that.noClick) {
        that.noClick = false;
        methods();
        setTimeout(function() {
            that.noClick = true;
        }, 2000)
    }
}

/**
 * 转换时间戳 比对时间
 * @param {String} start 开始时间
 * @param {String} end  结束时间
 * 默认必须结束之间大于等于开始时间
 * 修正IOS环境下new Date()兼容问题
 * 在ios里不支持 '-' 连接的日期，所以为了兼容ios，将日期转换为 '/' 连接的
 * new Date(date.replace(/-/g, "/"))
 */
export const compareDate = (start, end) => {
    let startTime = new Date(start.replace(/-/g, "/")).getTime();
    let endTime = new Date(end.replace(/-/g, "/")).getTime();
    return startTime > endTime;
}

/**
 * 初始化时间控件可选区间
 * @param {String} date 当前时间
 * 默认结束时间累加1年
 */
export const initDate = () => {
    let today = formatTime(new Date())[0].replace(/-/g, "/");
    let endYear = parseInt(formatTime(new Date())[0].split("/")[0]) + 1;
    store.state.startDate = `${today} 00:00`;
    store.state.endDate = `${endYear}-12-31 23:59`;
}

export const tip = (obj, fun) => {
    uni.showToast({
        title: obj.title || '',
        icon: obj.icon || 'none',
        duration: obj.duration || 1500,
        mask: true,
        success: () => {
            setTimeout(() => {
                fun && fun();
            }, obj.duration || 1500);
        }
    });
}

export const tipBack = (obj, fun) => {
    uni.showToast({
        title: obj.title || '',
        icon: obj.icon || 'none',
        duration: obj.duration || 1500,
        mask: true,
        success: () => {
            setTimeout(() => {
                fun()
            }, obj.duration || 1500);
        }
    });
}

export const toast = (obj, fun) => {
    uni.showModal({
        title: obj.title || '提示',
        content: obj.content,
        mask: true,
        success: (res) => {
            res.confirm && fun();
        },
    });
}

export const getMarker = () => {
    return setupMarker().then((res) => {
        if (res.data.code == 200) {
            let noticeNum = res.data.data.noreadTotal;
            if (noticeNum > 0) {
                uni.setTabBarBadge({
                    index: 1,
                    text: noticeNum > 99 ? "99+" : String(noticeNum),
                });
            } else {
                uni.removeTabBarBadge({
                    index: 1,
                });
            }

            // store.state.setBadgeNumber =
            //     Number(workbenchnum) + Number(noticeNum);
            //#ifdef APP-PLUS
            if (store.state.setBadgeNumber <= 0) {
                plus.runtime.setBadgeNumber(-1);
            } else {
                plus.runtime.setBadgeNumber(store.state.setBadgeNumber);
            }
            //#endif
        }
    });
}

export const setStorage = (data, key) => {
    // console.log(data);
    let getStorage = uni.getStorageSync(key);
    if (!getStorage) {
        getStorage = {};
    }
    getStorage[data.key] = data.value;
    // this.$nextTick(() => {
    uni.setStorageSync(key, getStorage);
    // });
}

/**
 * 非空判断
 * @param {Object} data
 */
export const isEmpty = (v) => {
    let bool = false;
    switch (typeof v) {
        case "string":
            bool = v === "";
            break;
        case "number":
            bool = v <= 0;
            break;
        case "object":
            if (v && v.length == 0) {
                bool = true;
            } else if (v && v.length > 0) {
                bool = v.map((x) => x.mobile === "" || x.username === "")[0];
            }
            break;
    }
    return bool;
}

/**
 * 表单验证
 * @param {Object} data
 * form：表单提交参数
 * rules：验证规则
 * submitParam：提交接口参数及跳转路径
 */
 export const verify = (form, rules, param, fun) => {
    // 非空条件验证
    for (let [k, v] of Object.entries(rules)) {
        if (v.required && isEmpty(form[k])) {
            tip({
                title: v.message
            });
            return;
        }

        // 条件验证
        if (v.required && rules[k].reg && !form[k].match(rules[k].reg)) {
            tip({
                title: rules[k].rmessage
            });
            return;
        }
    }

    uni.showModal({
        title: param.title || '提示',
        content: param.content || '确定提交?',
        mask: true,
        success: (res) => {
            res.confirm && submit(form, param, fun);
        },
    });
}

/**
 * 表单提交
 * @param {Object} data
 * form：表单提交参数
 * rules：验证规则
 * submitParam：提交接口参数及跳转路径
 */
 export const submit = (form, param, fun) => {
    showLoading('加载中');
    param.api(form).then(res => {
        if (res.data.code == 200) {
            hideLoading();
            tip({
                title: param.success
            }, () => {
                if (fun) {
                    fun(res.data.data);
                } else {
                    linkTo(param.url, param.type);
                }
            }, param.duration || 1500);
        }
    })
}

export const submitTip = (obj) => {
    uni.showToast({
        title: obj.title || '',
        icon: obj.icon || 'none',
        duration: obj.duration || 1500,
        mask: true,
        success: () => {
            setTimeout(() => {
                uni.navigateTo({
                    url: obj.url
                });
            }, 1500);
        }
    });
}

/**配对车的类型与图片 
 * carTypeId 传进来的车类型ID
 */

export const getCarImage = (carTypeId) => {
    let carType = uni.getStorageSync('carType');
    let obj = {};
    if (carType) {
        obj = carType.find(x => {
            return x.typevalue.split(',').includes(carTypeId)
        })
    }
    return !carTypeId || !carType || obj.image == '' ? '/static/img/car/car00.png' : obj.image;
}

/**
 * 路由跳转
 * @param {Object} data
 * url:跳转地址
 * @param {Object} params 
 * type:跳转方式
 * params:附带参数
 */
export const linkTo = (url, type = 'common', params) => {
    if (params) {
        let newParam = '';
        for (let [k, v] of Object.entries(params)) {
            newParam += `${k}=${v}&`
        }
        newParam = newParam.substring(0, newParam.lastIndexOf('&'));
        url += `?${newParam}`;
    }

    const typeList = {
        common: 'navigateTo',
        switch: 'switchTab',
        noback: 'reLaunch'
    }

    uni[typeList[type]]({
        url
    })
}

/* 时间累加 */
export const accDate = (day) => {
    const lw = new Date(new Date() - 1000 * 60 * 60 * 24 * day);
    const lastY = lw.getFullYear();
    const lastM = lw.getMonth() + 1;
    const lastD = lw.getDate();
    const hour = lw.getHours();
    const minute = lw.getMinutes();
    let startdate = lastY + "-" + (lastM < 10 ? "0" + lastM : lastM) + "-" + (lastD < 10 ? "0" + lastD : lastD) + " " + hour + ':' + minute;
    return startdate.replace(/-/g, '/');
}

/* 获取当前月份的天数 */
export const getMonthDays = () => {
    const date = new Date();
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    let d = new Date(year, month, 0);
    return d.getDate();
}

module.exports = {
    formatTime,
    throttleFunc,
    debounce,
    formatNumber,
    compareDate,
    initDate,
    tip,
    tipBack,
    toast,
    getMarker,
    setStorage,
    isEmpty,
    submitTip,
    linkTo,
    verify,
    submit,
    getCarImage,
    accDate,
    getMonthDays
}